<?php 

class My_FrontPlugin extends Zend_Controller_Plugin_Abstract{
	
	protected $fire_sql;
	protected $devel_mode; 
	
	private $rq;
	
	public function __construct($fire_sql = false,$devel_mode = false){
		$this->fire_sql = $fire_sql;
		$this->devel_mode = $devel_mode;
	}
	
	public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request){
		
			
		if($request->getParam('application_version')
			&& $request->getParam('application_version') != Utils::reg('version')
		){
			die(json_encode(array("success"=>false,"reason"=>"new_version","data"=>null,"rows"=>array(),"msg"=>"Wdrożono nową wersje aplikacji. Odśwież stronę.")));
		}
			
		/*
			$asset = $this->go_asset($request);
			if($this->devel_mode != true || !Utils::isIn($asset,array('ext/evalphp','ext/jsconfig','ext/cleancache'))){
				$this->rq = $request;
				
				$acl = $this->go_acl($request);
				$role = $this->go_auth();
				try {
					if(!$acl->has($asset) || !$acl->isAllowed($role,$asset)){
						$request->setControllerName('ext');
						$request->setActionName('failure');
						$request->setParam('acl_requested_action', $asset);
					}
				} catch (Exception $e){
					header('Content-Type: text/html; charset=utf-8');
					$msg = 'Błąd inicjacji uprawnień. '. $e->getMessage() . '(' .$e->getFile().' : '. $e->getLine().'). Spróbuj wyczyścić sessje i Zend_Cache dzielny developerze.';
					if(Utils::isAjax()){
						die("{success:false,msg:'$msg',rows:[],data:{}}");	
					} else {
						die("<h1>Błąd aplikacji</h1><h3>$msg</h3>");
					}
				}
			}
		*/
		if ($this->fire_sql)$this->go_fire_sql($request);
	}
	
	private function go_asset($request){
		$p = $request->getParams();
		$asset = $p["controller"]."/".$p["action"];
		return $asset;
	} 
	
	private function go_auth(){
		$auth = Zend_Auth::getInstance();
    	$auth->setStorage(new Zend_Auth_Storage_Session());
		if($auth->hasIdentity()){// czy nadal jest w bazie (moze czy jest aktywny)
			$u = new User();
			$id = Utils::myId();
    		$c = $u->fetchAll("user_active = 1 AND user_id = '$id'")->count();			
    		if($c==1)return Utils::whoAmI();
		}
		return Enum_Roles::GUEST;
	}
	
	private function go_acl(){
		$cache = Zend_Registry::get('cache');
		if(($acl = $cache->load('acl'.Utils::config('instancja'))) === false){
			$acl = new My_Acl($this->rq);
			if ($acl->has('index/index'))$cache->save($acl, 'acl'.Utils::config('instancja'));
		}
		return $acl;
	}
	
	private function go_fire_sql(Zend_Controller_Request_Abstract $request){
		$db = Zend_Db_Table_Abstract::getDefaultAdapter();
		$profiler = new Zend_Db_Profiler_Firebug('SQL debug');
		$profiler->setEnabled(true);
		$db->setProfiler($profiler);
	}
	
}

?>